// pages/addhouse/addHouse.js
var common = require('../../utils/common.js');
var address = require('../../utils/city.js');
var util = require('../../utils/util.js');
var animation
const app = getApp();
var that = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    houseId:"",
    name: "",
    areaId: "",
    street: "",
    latitude: "",
    longitude: "",
    description: "",
    circles: [],
    isAddRooms: true,//添加房间或批量添加
    floorList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],//楼层
    floorindex: 0,//楼层
    roomsunList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],//房间总数
    roomsunindex: 0,//房间总数下标
    prefix: '',//房间前缀
    /**
  * 页面的初始数据
  * 当前    provinces:所有省份
  * citys选择省对应的所有市,
  * areas选择市对应的所有区
  * provinces：当前被选中的省
  * city当前被选中的市
  * areas当前被选中的区
  */
    menuType: 0,
    begin: null,
    status: 1,
    end: null,
    isVisible: false,
    animationData: {},
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [19, 0, 0],
    provinces: [],
    citys: [],
    areas: [],
    province: '',
    city: '',
    area: ''
  },
  //批量添加选择
  switchChange: function (options) {
    this.setData({
      isAddRooms: !this.data.isAddRooms,
    })
  },
  // 楼层选择
  floorChange: function (e) {
    this.setData({
      floorindex: e.detail.value,
    })

  },
  //房间总数选择
  roomsunChange: function (e) {
    this.setData({
      roomsunindex: e.detail.value,
    })

  },
  //房间前缀输入框
  prefixInput: function (e) {
    this.setData({
      prefix: e.detail.value
    })
    console.log(this.data.prefix)
  },

  // 显示
  showMenuTap: function (e) {
    // console.log('selectState')
    //获取点击菜单的类型 1点击状态 2点击时间 
    var menuType = e.currentTarget.dataset.type
    // 如果当前已经显示，再次点击时隐藏
    if (this.data.isVisible == true) {
      this.startAnimation(false, -200)
      return
    }
    this.setData({
      menuType: menuType
    })
    this.startAnimation(true, 0)
  },
  hideMenuTap: function (e) {
    this.startAnimation(false, -200)
  },
  // 执行动画
  startAnimation: function (isShow, offset) {
    var that = this
    var offsetTem
    if (offset == 0) {
      offsetTem = offset
    } else {
      offsetTem = offset + 'rpx'
    }
    this.animation.translateY(offset).step()
    this.setData({
      animationData: this.animation.export(),
      isVisible: isShow
    })
    // console.log(that.data)
  },
  // 选择状态按钮
  selectState: function (e) {
    // console.log('selectState1')
    this.startAnimation(false, -200)
    var status = e.currentTarget.dataset.status
    this.setData({
      status: status
    })
    // console.log(this.data)

  },
  // 日志选择
  bindDateChange: function (e) {
    // console.log(e)
    if (e.currentTarget.dataset.type == 1) {
      this.setData({
        begin: e.detail.value
      })
    } else if (e.currentTarget.dataset.type == 2) {
      this.setData({
        end: e.detail.value
      })
    }
  },
  sureDateTap: function () {
    this.data.pageNo = 1
    this.startAnimation(false, -200)
  },


  // 点击所在地区弹出选择框
  selectDistrict: function (e) {

    // wx.chooseAddress({
    //   success: function (res) {
    //     that.setData({
    //       areaInfo: res.provinceName + res.cityName + res.countyName,
    //       street: res.detailInfo,
    //       areaId: res.nationalCode,
    //     })
    //     console.log(res.userName)
    //     console.log(res.postalCode)
    //     console.log(res.provinceName)
    //     console.log(res.cityName)
    //     console.log(res.countyName)
    //     console.log(res.detailInfo)
    //     console.log(res.nationalCode)
    //     console.log(res.telNumber)
    //     console.log(res)
    //   }
    // })
    var that = this
    // console.log('111111111')
    if (that.data.addressMenuIsShow) {
      return
    }
    that.startAddressAnimation(true)
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    // console.log(isShow)
    var that = this
    if (isShow) {
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(40 + 'vh').step()
    }
    that.setData({
      animationAddressMenu: that.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  // 点击地区选择取消按钮
  cityCancel: function (e) {
    this.startAddressAnimation(false)
  },
  // 点击地区选择确定按钮
  citySure: function (e) {
    var that = this
    var city = that.data.city
    var value = that.data.value
    that.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    var areaInfo = that.data.provinces[value[0]].name + ',' + that.data.citys[value[1]].name + ',' + that.data.areas[value[2]].name
    var aid = that.data.areas[value[2]].id;
    that.setData({
      areaInfo: areaInfo,
      areaId: aid,
    })
  },
  hideCitySelected: function (e) {
    // console.log(e)
    this.startAddressAnimation(false)
  },
  // 处理省市县联动逻辑
  cityChange: function (e) {
    // console.log(e)
    var value = e.detail.value
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var provinceNum = value[0]
    var cityNum = value[1]
    var countyNum = value[2]
    if (this.data.value[0] != provinceNum) {
      var id = provinces[provinceNum].id
      this.setData({
        value: [provinceNum, 0, 0],
        citys: address.citys[id],
        areas: address.areas[address.citys[id][0].id],
      })
    } else if (this.data.value[1] != cityNum) {
      var id = citys[cityNum].id
      this.setData({
        value: [provinceNum, cityNum, 0],
        areas: address.areas[citys[cityNum].id],
      })
    } else {
      this.setData({
        value: [provinceNum, cityNum, countyNum]
      })
    }
    // console.log(this.data)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    // 初始化动画变量
    var animation = wx.createAnimation({
      duration: 500,
      transformOrigin: "50% 50%",
      timingFunction: 'ease',
    })
    this.animation = animation;
    // 默认联动显示南宁
    // var id = address.provinces[19].id
    // var id = '450000';
    // this.setData({
    //   provinces: address.provinces,
    //   citys: address.citys[id],
    //   areas: address.areas[address.citys[id][0].id],
    //   value: [19, 0, 0],
    // })

    // console.log(this.data)
  },
  //名称输入框
  nameInput: function (e) {
    this.setData({
      name: e.detail.value,
    })
  },
  //街道输入框
  streetInput: function (e) {
    this.setData({
      street: e.detail.value,
    })
  },
  //备注输入框
  remarkInput: function (e) {
    this.setData({
      description: e.detail.value,
    })
  },
  //删除房源
  deleteHouse:function(){
    var that = this;
    console.log(that.data.houseId)
    wx.showModal({
      title: '提示',
      content: '确定要删除' + this.data.name+'吗？',
      success: function (res) {
        if (res.confirm) {
          common._get('/wx/house/delete', { houseId: that.data.houseId },
            //成功
            function (res) {
              console.log(res.data);
              if (res.data.success) {
                wx.showModal({
                  title: '提示',
                  content: '删除成功',
                })
                wx.setStorageSync('result', 'result')
                wx.navigateBack({
                })
                
              }
            });

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //提交房源
  submit: function () {
    if (this.data.name == '') {
      wx.showToast({
        title: '房源名称不能为空',
        image: '../../image/shibai.png'
      })
      return;
    }
    if (this.data.areaId == "") {
      wx.showToast({
        title: '请选择房屋地址',
        image: '../../image/shibai.png'
      })
      return;
    }
    if (this.data.longitude == "" && this.data.latitude == "") {
      wx.showToast({
        title: '请选择房屋位置',
        image: '../../image/shibai.png'
      })
      return;
    }
   
    var houseData = {
      id: this.data.id ? this.data.id : '',
      name: this.data.name,
      areaId: this.data.areaId,
      street: this.data.street,
      longitude: this.data.longitude,
      latitude: this.data.latitude,
      description: this.data.description,
    }
    console.log(houseData)
    if (this.data.isAddRooms) {
      common._get('/wx/house/addhouse', houseData,
        //成功
        function (res) {
          console.log(res.data);
          //手机获取信息是否成功
          if (res.data.success) {
            wx.showModal({
              title: '提示',
              content: '保存成功',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateBack();
                }
              }
            })
          }
        });
    } else {
      wx.showLoading({
        title: '提交中...',
      })
      houseData = {
        id: this.data.id ? this.data.id : '',
        name: this.data.name,
        areaId: this.data.areaId,
        street: this.data.street,
        longitude: this.data.longitude,
        latitude: this.data.latitude,
        description: this.data.description,
        floors: [],
      }
      //批量添加
      console.log('批量添加')
      var floorNum = this.data.floorList[this.data.floorindex];//楼层总数
      var roomNum = this.data.roomsunList[this.data.roomsunindex];//每层房间数
      var prefix = this.data.prefix;
      var floors = [];
      console.log(floorNum)
      for (var i=0;i<floorNum;i++) {
        var floor = i + 1;
        var obj = {
          name: floor,
          rooms: [],
          check: true,
        }
        for (var j =0;j< roomNum;j++) {
          var roomH = j + 1;
          var r = j < 10 ? '0' + roomH : j;
          var roomobj = {
            roomcode: prefix + floor + r,
            area: '',//面积
            houseType: '',//户型
            chargemode: '',//付款方式
            furniture: '',//配置
            config:-1,
            check: true,
          }
          obj.rooms.push(roomobj)
        }
        floors.push(obj);
      }
      houseData.floors = floors;
      wx.setStorageSync('roomsh', houseData);
      wx.hideLoading();
      wx.navigateTo({
        url: '../batchAddRoomsConfirm/batchAddRoomsConfirm',
      })
    }




  },
  //跳转到我的地图
  toMap: function () {
    wx.chooseLocation({
      success: function(res) {
        console.log(res)
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
          street: res.name
      })
      },
    })
  },
  //修改房源请求数据
  getHouseDetail: function (id) {
    console.log("请求数据:" + id)
    var that = this;
    common._get('/wx/house/detail', { houseId: id },

      function (res) {
        console.log(res.data)
        if (res.data.success) {
          that.setData({
            id: res.data.data.id,
            name: res.data.data.name,
            areaId: res.data.data.areaId,
            street: res.data.data.street,
            latitude: res.data.data.latitude,
            longitude: res.data.data.longitude,
            description: res.data.data.description,
            provincename: res.data.data.provincename,//省份名称
            cityname: res.data.data.cityname,//城市名称
            areaname: res.data.data.areaname,//区域
            areaInfo: res.data.data.provincename + res.data.data.cityname + res.data.data.areaname,
          })
          console.log(that.data);
          that.initCityData(res.data.data.provinceId, res.data.data.cityId, res.data.data.areaId)
        }
      })
  },

  initCityData: function (provincesId, citysId, areaId){
    var provincesN=19;
    var citysN = 0;
    var areaN = 0;
    //得到省份下标
    for (var i in address.provinces){
      if (address.provinces[i].id == provincesId){
        provincesN = i;
        break;
      }
    }
    //得到城市下标
    for (var i in address.citys[provincesId]) {
      if (address.citys[provincesId][i].id == citysId) {
        citysN = i;
        break;
      }
    }
    //得到城市下标
    for (var i in address.citys[provincesId]) {
      if (address.citys[provincesId][i].id == citysId) {
        citysN = i;
        break;
      }
    }
    //得到区域下标
    for (var i in address.areas[address.citys[provincesId][citysN].id]) {
      if (address.areas[address.citys[provincesId][citysN].id][i].id == areaId) {
        areaN = i;
        break;
      }
    }

    //设置为房源所在的地址
    this.setData({
      provinces: address.provinces,
      citys: address.citys[provincesId],
      areas: address.areas[address.citys[provincesId][citysN].id],
      value: [provincesN, citysN, areaN]
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    that = this;
    //获取房子细节
    var houseId = wx.getStorageSync('houseid')
    wx.removeStorageSync('houseid');
    if (houseId) {
      wx.setNavigationBarTitle({
        title: '修改房源',
      })
      this.setData({
        houseId: houseId
      })
      this.getHouseDetail(houseId)
    }

    // var id = address.provinces[19].id
    var id = '450000';
    this.setData({
      provinces: address.provinces,
      citys: address.citys[id],
      areas: address.areas[address.citys[id][0].id],
      // value: [19, 0, 0],
    })
    this.initCityData('450000','','')


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // var location = wx.getStorageSync('location')
    // wx.removeStorageSync('location')
    // console.log(location)
    // if (location) {
    //   that.setData({
    //     longitude: location[0].longitude,
    //     latitude: location[0].latitude,
    //   })
    //   console.log(this.data.latitude.length);
    // }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})